package com.ruicar.afs.cloud.channel.channelworkflow.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruicar.afs.cloud.channel.cardealer.common.Constants;
import com.ruicar.afs.cloud.channel.cardealer.condition.CarDealerCondition;
import com.ruicar.afs.cloud.channel.cardealer.condition.DirectCarDealerCondition;
import com.ruicar.afs.cloud.channel.cardealer.entity.ChannelCoopeCardealerTemp;
import com.ruicar.afs.cloud.channel.cardealer.entity.CommonCarDealer;
import com.ruicar.afs.cloud.channel.cardealer.entity.DirectCarDealer;
import com.ruicar.afs.cloud.channel.cardealer.service.CarDealerService;
import com.ruicar.afs.cloud.channel.cardealer.service.ChannelCoopeCardealerService;
import com.ruicar.afs.cloud.channel.cardealer.service.DirectCarDealerService;
import com.ruicar.afs.cloud.channel.channelworkflow.condition.ChannelOnlineWorkFlowCondition;
import com.ruicar.afs.cloud.channel.channelworkflow.entity.WorkTaskAssign;
import com.ruicar.afs.cloud.channel.channelworkflow.entity.WorkTaskCreated;
import com.ruicar.afs.cloud.channel.channelworkflow.entity.WorkTaskDetail;
import com.ruicar.afs.cloud.channel.channelworkflow.service.WorkTaskApproveRecordService;
import com.ruicar.afs.cloud.channel.channelworkflow.service.WorkTaskAssignService;
import com.ruicar.afs.cloud.channel.channelworkflow.service.WorkTaskCreatedService;
import com.ruicar.afs.cloud.channel.channelworkflow.service.WorkTaskDetailService;
import com.ruicar.afs.cloud.channel.channelworkflow.vo.CarDealerWorkTaskVo;
import com.ruicar.afs.cloud.channel.common.enums.ChannelAfsFlowEnum;
import com.ruicar.afs.cloud.channel.common.feign.ChannelUseCaseService;
import com.ruicar.afs.cloud.channel.common.until.ChannelConfig;
import com.ruicar.afs.cloud.channel.online.entity.*;
import com.ruicar.afs.cloud.channel.online.service.*;
import com.ruicar.afs.cloud.channel.online.untils.ChannelOnlineConstants;
import com.ruicar.afs.cloud.channel.register.service.ChannelBaseInfoService;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.log.annotation.SysLog;
import com.ruicar.afs.cloud.common.core.security.service.AfsUser;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.image.entity.ComAttachmentFile;
import com.ruicar.afs.cloud.image.service.ComAttachmentFileService;
import com.ruicar.afs.cloud.workflow.api.dto.flowprocess.WorkFlowResponse;
import com.ruicar.afs.cloud.workflow.api.dto.flowprocess.request.QueryFLowCmdRequest;
import com.ruicar.afs.cloud.workflow.api.dto.flowprocess.request.TaskSubmitRequest;
import com.ruicar.afs.cloud.workflow.api.dto.flowprocess.response.FlowCmdBean;
import com.ruicar.afs.cloud.workflow.gwt.service.WorkflowService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

import static com.ruicar.afs.cloud.channel.cardealer.common.Constants.COMMONCARDEALERFILE;
import static com.ruicar.afs.cloud.channel.cardealer.common.Constants.DIRECTCARDEALERFILE;
import static com.ruicar.afs.cloud.channel.online.untils.ChannelOnlineConstants.CARDEALER;
import static com.ruicar.afs.cloud.channel.online.untils.ChannelOnlineConstants.MAIN;

/**
 * @author: sang jian
 * @date: 2020/7/21 15:45
 * @description:
 */

@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/carDealerWorkFlow")
@Api(value = "carDealerWorkFlow", description = "车商审批")
public class CarDealerWorkflowController {

    private final WorkTaskAssignService workTaskAssignService;

    private final WorkTaskCreatedService workTaskCreatedService;
    private ChannelMainBrandService channelMainBrandService;
    private final WorkTaskDetailService workTaskDetailService;
    private final WorkTaskApproveRecordService workTaskApproveRecordService;
    private final WorkflowService workflowService;
    private CarDealerService carDealerService;
    private ChannelConfig channelConfig;
    private ChannelUseCaseService channelUseCaseService;
    private DirectCarDealerService directCarDealerService;
    private ChannelBaseInfoService channelBaseInfoService;
    private ChannelRiskInfoService channelRiskInfoService;
    private ChannelQuotaInfoService channelQuotaInfoService;
    private ChannelAuthorizeRegionService channelAuthorizeRegionService;
    private ChannelAuthorizeVehicleTempService channelAuthorizeVehicleTempService;
    private ChannelAccountInfoService channelAccountInfoService;
    private final ComAttachmentFileService comAttachmentFileService;
    private ChannelCoopeCardealerService channelCoopeCardealerService;

    @PostMapping(value = "/getCommonCarDealerInfoByCondition")
    @ApiOperation(value = "多条件分页普通车商信息列表")
    public IResponse getByCondition(@RequestBody ChannelOnlineWorkFlowCondition condition) {
        Page page = new Page(condition.getPageNumber(), condition.getPageSize());
        //获取当前用户角色名
        condition.setUserRoles(SecurityUtils.getRoles());
        IPage<List<CarDealerWorkTaskVo>> commoncarDealerWorkflowInfoList = workTaskAssignService.getCommoncarDealerWorkflowInfo(page, condition);
        return IResponse.success(commoncarDealerWorkflowInfoList);
    }

    @PostMapping(value = "/getDirectCarDealerWorkFlowDataByCondition")
    @ApiOperation(value = "多条件分页直营车商信息列表")
    public IResponse getDirectCarDealerWorkFlowDataByCondition(@RequestBody ChannelOnlineWorkFlowCondition condition) {
        Page page = new Page(condition.getPageNumber(), condition.getPageSize());
        //获取当前用户角色
        condition.setUserRoles(SecurityUtils.getRoles());
        List<String> roleCodeList = SecurityUtils.getUser().getRoleCodeList();
        IPage<List<CarDealerWorkTaskVo>> carDealerWorkflowInfoList = workTaskAssignService.getDirectCarDealerWorkFlowDataByCondition(page, condition);
        List <Object> result = new ArrayList<>();
        result.add(carDealerWorkflowInfoList);
        result.add(roleCodeList);
        return IResponse.success(result);
    }


    @PostMapping(value = "/approveCommonCarDealerWorkFlow")
    @ApiOperation(value = "提交普通车商审批流程")
    @SysLog("提交普通车商审批流程")
    @Transactional(rollbackFor = Exception.class)
    public IResponse approveCommonCarDealerWorkFlow(@RequestBody ChannelOnlineWorkFlowCondition condition) throws JsonProcessingException {
        WorkTaskAssign assgin = workTaskAssignService.getOne(Wrappers.<WorkTaskAssign>query().lambda().eq(WorkTaskAssign::getBizDataId, condition.getBizDataId()));
        WorkTaskCreated created = workTaskCreatedService.getOne(Wrappers.<WorkTaskCreated>query().lambda().eq(WorkTaskCreated::getBizDataId, condition.getBizDataId()));
        WorkTaskDetail detail = workTaskDetailService.getOne(Wrappers.<WorkTaskDetail>query().lambda().eq(WorkTaskDetail::getBizDataId, condition.getBizDataId()));

        //提交完成之后删除其他人员代办
        List<WorkTaskAssign> assignList = workTaskAssignService.list(Wrappers.<WorkTaskAssign>query().lambda().eq(WorkTaskAssign::getBizDataId, condition.getBizDataId()));

        CommonCarDealer commonCarDealer = carDealerService.getOne(Wrappers.<CommonCarDealer>query().lambda().eq(CommonCarDealer::getId, condition.getCarDealerId()));
        //关联合作商的id
        Long channelId = condition.getChannelId();
        String longitudeLatitudeRange = condition.getLongitudeLatitudeRange();
        String remark = condition.getRemark();


        TaskSubmitRequest taskSubmitRequest = new TaskSubmitRequest();
        taskSubmitRequest.setGwtUserId(assgin.getAssignId());
        taskSubmitRequest.setAfsFlowKey(created.getAfsFlowKey());
        taskSubmitRequest.setBizDataId(created.getBizDataId());
        QueryFLowCmdRequest request = new QueryFLowCmdRequest();
        request.setFlowInstanceId(created.getFlowInstanceId());
        WorkFlowResponse<List<FlowCmdBean>> cmdResponse = workflowService.queryFlowCmd(request);
        List<FlowCmdBean> cmdList = cmdResponse.getAfsData();
        FlowCmdBean cmd = workTaskCreatedService.channelApprove(condition.getApprove(), cmdList);

        if (cmd != null) {
            log.info("==================================提交工作流开始==================================》");
            taskSubmitRequest.setCmdId(cmd.getId());

            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(commonCarDealer);
            JSONObject cancelJson = JSONObject.parseObject(json);

            workflowService.taskSubmit(taskSubmitRequest,cancelJson);
            condition.setTaskName(assgin.getTaskName());
            workTaskApproveRecordService.approveSave(condition, cmd);
            log.info("==================================业务逻辑处理开始==================================》");
            String taskMemo = created.getTaskMemo();

            if (!StrUtil.isBlank(taskMemo)) {
                JSONObject jsonMemo = (JSONObject) JSONObject.parse(taskMemo);
                String memo = (String) jsonMemo.get(AfsEnumUtil.key(ChannelAfsFlowEnum.NODE_LABEL));

                if (AfsEnumUtil.desc(ChannelAfsFlowEnum.CHANNEL_BACK).equals(cmd.getCmdDis())) {
                    //首节点
                    if (ChannelOnlineConstants.FIRST_NODE.equals(memo)) {
                        //首节点(退回特殊处理逻辑)：退回
                        List<ChannelCoopeCardealerTemp> coopeCardealerTemps = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealerTemp>query().lambda()
                                .eq(ChannelCoopeCardealerTemp::getCardealerType, Constants.COMMONCARDEALER)
                                .eq(ChannelCoopeCardealerTemp::getChannelId, channelId)
                                .eq(ChannelCoopeCardealerTemp::getCardealerId, commonCarDealer.getId())
                        );
                        //改关联表状态
                        if (coopeCardealerTemps.size() > 0) {
                            for (ChannelCoopeCardealerTemp temp : coopeCardealerTemps) {
                                temp.setStatus(Constants.DRAWBACK);
                                temp.setApproveRemark(remark);
                                channelCoopeCardealerService.updateById(temp);
                            }
                        }
                        //查一下是否有这家车商 有的话 车商状态不变,没有的话就改车商状态为退回
                        List<ChannelCoopeCardealerTemp> coopeCardealerTemps2 = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealerTemp>query().lambda()
                                .eq(ChannelCoopeCardealerTemp::getCardealerType, Constants.COMMONCARDEALER)
                                .ne(ChannelCoopeCardealerTemp::getChannelId, channelId)
                                .eq(ChannelCoopeCardealerTemp::getCardealerId, commonCarDealer.getId())
                        );
                        if (coopeCardealerTemps2.size() == 0) {
                            //车商没跟其他合作商关联,改车商状态
                            commonCarDealer.setStatus(Constants.DRAWBACK);
                            carDealerService.updateById(commonCarDealer);
                        }
                        workTaskDetailService.removeById(detail);
                        workTaskCreatedService.removeById(created);
                    }
                }
                if (AfsEnumUtil.desc(ChannelAfsFlowEnum.CHANNEL_REFUSE).equals(cmd.getCmdDis())) {
                    //首节点//拒绝
                    List<ChannelCoopeCardealerTemp> coopeCardealerTemps = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealerTemp>query().lambda()
                            .eq(ChannelCoopeCardealerTemp::getCardealerType, Constants.COMMONCARDEALER)
                            .eq(ChannelCoopeCardealerTemp::getChannelId, channelId)
                            .eq(ChannelCoopeCardealerTemp::getCardealerId, commonCarDealer.getId())
                    );
                    //改关联表状态
                    if (coopeCardealerTemps.size() > 0) {
                        for (ChannelCoopeCardealerTemp temp : coopeCardealerTemps) {
                            temp.setStatus(Constants.REFUSE);
                            temp.setApproveRemark(remark);
                            channelCoopeCardealerService.updateById(temp);
                        }
                    }
                    //查一下是否有这家车商 有的话 车商状态不变,没有的话就改车商状态为退回
                    List<ChannelCoopeCardealerTemp> coopeCardealerTemps2 = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealerTemp>query().lambda()
                            .eq(ChannelCoopeCardealerTemp::getCardealerType, Constants.COMMONCARDEALER)
                            .ne(ChannelCoopeCardealerTemp::getChannelId, channelId)
                            .eq(ChannelCoopeCardealerTemp::getCardealerId, commonCarDealer.getId())
                    );
                    if (coopeCardealerTemps2.size() == 0) {
                        //车商没跟其他合作商关联,改车商状态
                        commonCarDealer.setStatus(Constants.REFUSE);
                        commonCarDealer.setLongitudeLatitudeRange(condition.getLongitudeLatitudeRange());
                        carDealerService.updateById(commonCarDealer);
                    }
                }
                if (AfsEnumUtil.desc(ChannelAfsFlowEnum.CHANNEL_SUBMIT).equals(cmd.getCmdDis())) {
                    //审批通过
                    //同步普通车商到案件服务用的
                    CarDealerCondition commonCarDealerToCase = new CarDealerCondition();
                    commonCarDealer.setLongitudeLatitudeRange(longitudeLatitudeRange);
                    //审批通过,改关联表的状态,然后看一下是否有已启用的同一车商,如果有 ,并进去并更新,如果没有 那就只更新车商状态
                    List<CommonCarDealer> commonCarDealerList = carDealerService.list(Wrappers.<CommonCarDealer>query().lambda()
                            .eq(CommonCarDealer::getStatus, Constants.ENABLED)
                            .eq(CommonCarDealer::getSocUniCrtCode, commonCarDealer.getSocUniCrtCode())
                    );

                    List<ChannelCoopeCardealerTemp> coopeCardealerTemps = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealerTemp>query().lambda()
                            .eq(ChannelCoopeCardealerTemp::getCardealerType, Constants.COMMONCARDEALER)
                            .eq(ChannelCoopeCardealerTemp::getChannelId, channelId)
                            .eq(ChannelCoopeCardealerTemp::getCardealerId, commonCarDealer.getId())
                    );

                    Long carDealerId = null;
                    //更新品牌
                    List<ChannelMainBrand> mainBrands = channelMainBrandService.list(Wrappers.<ChannelMainBrand>query().lambda()
                            .eq(ChannelMainBrand::getChannelBelong, Constants.COMMONCARDEALER)
                            .eq(ChannelMainBrand::getChannelId, commonCarDealer.getId())
                    );
                    if (commonCarDealerList.size() > 0) {
                        //有这个车商,并进去并且更新品牌信息
                        carDealerId = commonCarDealerList.get(0).getId();

                        //更新附件
                        List<ComAttachmentFile> fileList = comAttachmentFileService.list(Wrappers.<ComAttachmentFile>query().lambda()
                                .eq(ComAttachmentFile::getBelongNo, channelId.toString())
                                .eq(ComAttachmentFile::getBusiNo, commonCarDealer.getId()));
                        if(CollectionUtil.isNotEmpty(fileList)){
                            for (ComAttachmentFile file : fileList){
                                file.setBusiNo(carDealerId.toString());
                            }
                            comAttachmentFileService.updateBatchById(fileList);
                        }


                        //删品牌
                        channelMainBrandService.remove(Wrappers.<ChannelMainBrand>query().lambda()
                                .eq(ChannelMainBrand::getChannelBelong, Constants.COMMONCARDEALER)
                                .eq(ChannelMainBrand::getChannelId, carDealerId)
                        );
                        if (mainBrands.size() > 0) {
                            for (ChannelMainBrand brand : mainBrands) {
                                brand.setChannelId(carDealerId);
                            }
                            channelMainBrandService.updateBatchById(mainBrands);
                        }
                        carDealerService.removeById(commonCarDealer.getId());
                        commonCarDealer.setId(carDealerId);
                        commonCarDealer.setStatus(Constants.ENABLED);
                        carDealerService.updateById(commonCarDealer);
                    } else {
                        //没有这个车商,更新状态即可
                        commonCarDealer.setStatus(Constants.ENABLED);
                        carDealerService.updateById(commonCarDealer);
                    }
                    //改关联表状态
                    if (coopeCardealerTemps.size() > 0) {
                        for (ChannelCoopeCardealerTemp temp : coopeCardealerTemps) {
                            temp.setStatus(Constants.ENABLED);
                            temp.setApproveRemark(remark);
                            temp.setCardealerId(commonCarDealer.getId());
                            channelCoopeCardealerService.updateById(temp);
                        }
                    }
                    //同步到案件服务
                    commonCarDealerToCase.setChannelCoopeCardealerTemp(coopeCardealerTemps.get(0));
                    commonCarDealerToCase.setCommonCarDealer(commonCarDealer);
                    commonCarDealerToCase.setChannelMainBrandList(mainBrands);
                    //******************同步到案件服务**************
                    saveCommonCarDealerInfoToCase(commonCarDealerToCase);
                }
            }
            //删除剩余节点数据信息
            for (int i = 0; i < assignList.size(); i++) {
                workTaskAssignService.removeById(assignList.get(i).getId());
            }
            return IResponse.success("提交成功");
        } else {
            return IResponse.fail("提交失败,提交指令异常，请确认！");
        }

    }


    public void saveCommonCarDealerInfoToCase(CarDealerCondition condition) {
        //同步数据到案件服务
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("clientId", channelConfig.getCaseClientId());
        headers.put("clientSecret", channelConfig.getCaseClientSecret());
        Assert.isTrue((boolean)channelUseCaseService.saveCommonCarDealer(condition, headers).getData(),"操作失败,请重试!");
    }


    @PostMapping(value = "/approveDirectCarDealerWorkFlow")
    @ApiOperation(value = "提交直营车商审批流程")
    @SysLog("提交直营车商审批流程")
    @Transactional(rollbackFor = Exception.class)
    public IResponse approveDirectCarDealerWorkFlow(@RequestBody ChannelOnlineWorkFlowCondition condition) throws JsonProcessingException {
        WorkTaskAssign assgin = workTaskAssignService.getOne(Wrappers.<WorkTaskAssign>query().lambda().eq(WorkTaskAssign::getBizDataId, condition.getBizDataId()));
        WorkTaskCreated created = workTaskCreatedService.getOne(Wrappers.<WorkTaskCreated>query().lambda().eq(WorkTaskCreated::getBizDataId, condition.getBizDataId()));
        WorkTaskDetail detail = workTaskDetailService.getOne(Wrappers.<WorkTaskDetail>query().lambda().eq(WorkTaskDetail::getBizDataId, condition.getBizDataId()));

        //提交完成之后删除其他人员代办
        List<WorkTaskAssign> assignList = workTaskAssignService.list(Wrappers.<WorkTaskAssign>query().lambda().eq(WorkTaskAssign::getBizDataId, condition.getBizDataId()));
        //车商信息
        DirectCarDealer directCarDealer = directCarDealerService.getOne(Wrappers.<DirectCarDealer>query().lambda().eq(DirectCarDealer::getId, condition.getCarDealerId()));
        //关联合作商的id
        Long channelId = condition.getChannelId();
        //经纬度范围
        String longitudeLatitudeRange = condition.getLongitudeLatitudeRange();
        String remark = condition.getRemark();
        if(longitudeLatitudeRange !=null && longitudeLatitudeRange !=""){
            directCarDealer.setLongitudeLatitudeRange(longitudeLatitudeRange);
            directCarDealerService.updateById(directCarDealer);
        }
        if(remark !=null && remark !=""){
            List<ChannelCoopeCardealerTemp> coopeCardealerTemps = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealerTemp>query().lambda()
                    .eq(ChannelCoopeCardealerTemp::getCardealerType, Constants.DIRECTCARDEALER)
                    .eq(ChannelCoopeCardealerTemp::getChannelId, channelId)
                    .eq(ChannelCoopeCardealerTemp::getCardealerId, directCarDealer.getId())
            );
            //改关联表状态
            if (coopeCardealerTemps.size() > 0) {
                for (ChannelCoopeCardealerTemp temp : coopeCardealerTemps) {
                    temp.setApproveRemark(remark);
                    channelCoopeCardealerService.updateById(temp);
                }
            }
        }
        //获取合作商的汇款账号信息
        DirectCarDealer channelBaseInfo = directCarDealerService.getById(channelId);
        //ChannelBaseInfo channelBaseInfo = channelBaseInfoService.getById(channelId);
        String paymentObject = channelBaseInfo.getPaymentObject();
        if (paymentObject == null || paymentObject == "") {
            return IResponse.fail("合作商汇款信息异常!");
        }

        TaskSubmitRequest taskSubmitRequest = new TaskSubmitRequest();
        taskSubmitRequest.setGwtUserId(assgin.getAssignId());
        taskSubmitRequest.setAfsFlowKey(created.getAfsFlowKey());
        taskSubmitRequest.setBizDataId(created.getBizDataId());
        QueryFLowCmdRequest request = new QueryFLowCmdRequest();
        request.setFlowInstanceId(created.getFlowInstanceId());
        WorkFlowResponse<List<FlowCmdBean>> cmdResponse = workflowService.queryFlowCmd(request);
        List<FlowCmdBean> cmdList = cmdResponse.getAfsData();
        FlowCmdBean cmd = workTaskCreatedService.channelApprove(condition.getApprove(), cmdList);

        if (cmd != null) {
            log.info("==================================提交工作流开始==================================》");
            taskSubmitRequest.setCmdId(cmd.getId());

            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(directCarDealer);
            JSONObject cancelJson = JSONObject.parseObject(json);
            cancelJson.put(AfsEnumUtil.key(ChannelAfsFlowEnum.PAYMENT_OBJECT), paymentObject);

            //获取该合作商下所有审核中的收款账号
            List<ChannelReceivablesAccountTemp> inApproveAccountTempList = channelAccountInfoService.list(Wrappers.<ChannelReceivablesAccountTemp>query().lambda()
                    .eq(ChannelReceivablesAccountTemp::getChannelId, directCarDealer.getId())
                    .eq(ChannelReceivablesAccountTemp::getStatus, Constants.REVIEW)
            );

            workflowService.taskSubmit(taskSubmitRequest, cancelJson);
            condition.setTaskName(assgin.getTaskName());
            workTaskApproveRecordService.approveSave(condition, cmd);
            log.info("==================================业务逻辑处理开始==================================》");
            String taskMemo = created.getTaskMemo();
            if (!StrUtil.isBlank(taskMemo)) {
                JSONObject jsonMemo = (JSONObject) JSONObject.parse(taskMemo);
                String memo = (String) jsonMemo.get(AfsEnumUtil.key(ChannelAfsFlowEnum.NODE_LABEL));

                if (AfsEnumUtil.desc(ChannelAfsFlowEnum.CHANNEL_BACK).equals(cmd.getCmdDis())) {
                    //首节点
                    if (ChannelOnlineConstants.FIRST_NODE.equals(memo)) {
                        //首节点(退回特殊处理逻辑)：退回
                        List<ChannelCoopeCardealerTemp> coopeCardealerTemps = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealerTemp>query().lambda()
                                .eq(ChannelCoopeCardealerTemp::getCardealerType, Constants.DIRECTCARDEALER)
                                .eq(ChannelCoopeCardealerTemp::getChannelId, channelId)
                                .eq(ChannelCoopeCardealerTemp::getCardealerId, directCarDealer.getId())
                        );
                        //改关联表状态
                        if (coopeCardealerTemps.size() > 0) {
                            for (ChannelCoopeCardealerTemp temp : coopeCardealerTemps) {
                                temp.setStatus(Constants.DRAWBACK);
                                temp.setApproveRemark(remark);
                                channelCoopeCardealerService.updateById(temp);
                            }
                        }
                        //查一下是否有这家车商 有的话 车商状态不变,没有的话就改车商状态为退回
                        List<ChannelCoopeCardealerTemp> coopeCardealerTemps2 = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealerTemp>query().lambda()
                                .eq(ChannelCoopeCardealerTemp::getCardealerType, Constants.DIRECTCARDEALER)
                                .ne(ChannelCoopeCardealerTemp::getChannelId, channelId)
                                .eq(ChannelCoopeCardealerTemp::getCardealerId, directCarDealer.getId())
                        );
                        if (coopeCardealerTemps2.size() == 0) {
                            //车商没跟其他合作商关联,改车商状态
                            if (directCarDealer.getChannelStatus() != null) {
                                directCarDealer.setChannelStatus(Constants.DRAWBACK);
                            }
                            if (directCarDealer.getChannelStatusOldCar() != null) {
                                directCarDealer.setChannelStatusOldCar(Constants.DRAWBACK);
                            }
                            directCarDealerService.updateById(directCarDealer);
                            //改收款账号状态为退回
                            if (CARDEALER.equals(paymentObject)) {
                                if (inApproveAccountTempList.size() > 0) {
                                    for (ChannelReceivablesAccountTemp accountTemp : inApproveAccountTempList) {
                                        accountTemp.setStatus(Constants.DRAWBACK);
                                        channelAccountInfoService.updateById(accountTemp);
                                    }
                                }
                            }
                        }
                        workTaskDetailService.removeById(detail);
                        workTaskCreatedService.removeById(created);
                    }
                }
                if (AfsEnumUtil.desc(ChannelAfsFlowEnum.CHANNEL_REFUSE).equals(cmd.getCmdDis())) {
                    //首节点//拒绝
                    List<ChannelCoopeCardealerTemp> coopeCardealerTemps = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealerTemp>query().lambda()
                            .eq(ChannelCoopeCardealerTemp::getCardealerType, Constants.DIRECTCARDEALER)
                            .eq(ChannelCoopeCardealerTemp::getChannelId, channelId)
                            .eq(ChannelCoopeCardealerTemp::getCardealerId, directCarDealer.getId())
                    );
                    //改关联表状态
                    if (coopeCardealerTemps.size() > 0) {
                        for (ChannelCoopeCardealerTemp temp : coopeCardealerTemps) {
                            temp.setStatus(Constants.REFUSE);
                            temp.setApproveRemark(remark);
                            channelCoopeCardealerService.updateById(temp);
                        }
                    }
                    //查一下是否有这家车商 有的话 车商状态不变,没有的话就改车商状态为退回
                    List<ChannelCoopeCardealerTemp> coopeCardealerTemps2 = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealerTemp>query().lambda()
                            .eq(ChannelCoopeCardealerTemp::getCardealerType, Constants.DIRECTCARDEALER)
                            .ne(ChannelCoopeCardealerTemp::getChannelId, channelId)
                            .eq(ChannelCoopeCardealerTemp::getCardealerId, directCarDealer.getId())
                    );
                    if (coopeCardealerTemps2.size() == 0) {
                        //车商没跟其他合作商关联,改车商状态
                        if (directCarDealer.getChannelStatus() != null) {
                            directCarDealer.setChannelStatus(Constants.REFUSE);
                        }
                        if (directCarDealer.getChannelStatusOldCar() != null) {
                            directCarDealer.setChannelStatusOldCar(Constants.REFUSE);
                        }
                        directCarDealerService.updateById(directCarDealer);
                        //改收款账号状态为退回
                        if (CARDEALER.equals(paymentObject)) {
                            if (inApproveAccountTempList.size() > 0) {
                                for (ChannelReceivablesAccountTemp accountTemp : inApproveAccountTempList) {
                                    accountTemp.setStatus(Constants.REFUSE);
                                    channelAccountInfoService.updateById(accountTemp);
                                }
                            }
                        }
                    }
                }
                String node = "end";
                if (MAIN.equals(paymentObject)) {
                    node = "first";
                }
                if (AfsEnumUtil.desc(ChannelAfsFlowEnum.CHANNEL_SUBMIT).equals(cmd.getCmdDis()) && node.equals(memo)) {
                    //审批通过
                    //同步直营车商到案件服务用的
                    DirectCarDealerCondition directCarDealerToCase = new DirectCarDealerCondition();
                    //directCarDealer.setLongitudeLatitudeRange(longitudeLatitudeRange);
                    //审批通过,改关联表的状态,然后看一下是否有已启用的同一车商,如果有 ,并进去并更新,如果没有 那就只更新车商状态
                    //获取该合作商下的所有已启用收款账号信息
                    List<ChannelReceivablesAccountTemp> enableAccountTempList = channelAccountInfoService.list(Wrappers.<ChannelReceivablesAccountTemp>query().lambda()
                            .eq(ChannelReceivablesAccountTemp::getChannelId, directCarDealer.getId())
                            .eq(ChannelReceivablesAccountTemp::getStatus, Constants.ENABLED)
                    );


                    List<DirectCarDealer> dealerList = directCarDealerService.list(Wrappers.<DirectCarDealer>query().lambda()
                            .eq(DirectCarDealer::getSocUniCrtCode, directCarDealer.getSocUniCrtCode())
                            .and(wrapper1 -> wrapper1.eq(DirectCarDealer::getChannelStatusOldCar, Constants.ENABLED)
                                    .or(wrapper2 -> wrapper2.eq(DirectCarDealer::getChannelStatus, Constants.ENABLED))
                            )
                    );

                    List<ChannelCoopeCardealerTemp> coopeCardealerTemps = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealerTemp>query().lambda()
                            .eq(ChannelCoopeCardealerTemp::getCardealerType, Constants.DIRECTCARDEALER)
                            .eq(ChannelCoopeCardealerTemp::getChannelId, channelId)
                            .eq(ChannelCoopeCardealerTemp::getCardealerId, directCarDealer.getId())
                    );

                    Long carDealerId = null;
                    //更新品牌
                    List<ChannelMainBrand> mainBrands = channelMainBrandService.list(Wrappers.<ChannelMainBrand>query().lambda()
                            .eq(ChannelMainBrand::getChannelBelong, Constants.DIRECTCARDEALER)
                            .eq(ChannelMainBrand::getChannelId, directCarDealer.getId())
                    );
                    //风控信息
                    List<ChannelRiskInfoTemp> riskInfoTempList = channelRiskInfoService.list(Wrappers.<ChannelRiskInfoTemp>query().lambda()
                            .eq(ChannelRiskInfoTemp::getChannelId, directCarDealer.getId()));

                    //保证金channelQuotaInfoService
                    List<ChannelQuotaInfoTemp> quotaInfoTempList = channelQuotaInfoService.list(Wrappers.<ChannelQuotaInfoTemp>query().lambda()
                            .eq(ChannelQuotaInfoTemp::getChannelId, directCarDealer.getId()));

                    //授权区域channelAuthorizeRegionService
                    List<ChannelAuthorizeRegionTemp> regionTempList = channelAuthorizeRegionService.list(Wrappers.<ChannelAuthorizeRegionTemp>query().lambda()
                            .eq(ChannelAuthorizeRegionTemp::getChannelId, directCarDealer.getId()));

                    //授权车型channelAuthorizeVehicleTempService
                    List<ChannelAuthorizeVehicleTemp> vehicleTempList = channelAuthorizeVehicleTempService.list(Wrappers.<ChannelAuthorizeVehicleTemp>query().lambda()
                            .eq(ChannelAuthorizeVehicleTemp::getChannelId, directCarDealer.getId()));

                    if (dealerList.size() > 0) {
                        //有这个车商,并进去并且更新品牌信息,更新账户信息
                        carDealerId = dealerList.get(0).getId();

                        if (node.equals("end")) {
                            //需要财务审核
                            //老账号
                            List<ChannelReceivablesAccountTemp> accountTempListOld = channelAccountInfoService.list(Wrappers.<ChannelReceivablesAccountTemp>query().lambda()
                                    .eq(ChannelReceivablesAccountTemp::getChannelId, carDealerId)
                                    .in(ChannelReceivablesAccountTemp::getStatus, Constants.ENABLED, Constants.DRAFT)
                            );
                            if (accountTempListOld.size() > 0 && enableAccountTempList.size() > 0) {
                                for (ChannelReceivablesAccountTemp oldTemp : accountTempListOld) {
                                    for (ChannelReceivablesAccountTemp newTemp : enableAccountTempList) { //已启用的新账号
                                        if (oldTemp.getAccountAttribute().equals(newTemp.getAccountAttribute()) && oldTemp.getCollectionType().equals(newTemp.getCollectionType())) {
                                            //老账户停用,新账号启用
                                            oldTemp.setStatus(Constants.DISABLE);
                                            newTemp.setStatus(Constants.ENABLED);
                                            newTemp.setChannelId(carDealerId);
                                            channelAccountInfoService.updateById(oldTemp);
                                            channelAccountInfoService.updateById(newTemp);
                                        }
                                    }
                                }
                                //老账户处理完了 开始新账号处理
                                if (enableAccountTempList.size() > 0 && inApproveAccountTempList.size() > 0) {
                                    for (ChannelReceivablesAccountTemp temp1 : inApproveAccountTempList) {
                                        for (ChannelReceivablesAccountTemp temp2 : enableAccountTempList) { //已启用的
                                            if (temp1.getAccountAttribute().equals(temp2.getAccountAttribute()) && temp1.getCollectionType().equals(temp2.getCollectionType())) {
                                                //同类型的账号,把 审核中的状态设置成启用, 把已启用的状态设置成停用
                                                temp1.setStatus(Constants.ENABLED);
                                                temp2.setStatus(Constants.DISABLE);
                                                temp1.setChannelId(carDealerId);
                                                temp2.setChannelId(carDealerId);
                                                channelAccountInfoService.updateById(temp1);
                                                channelAccountInfoService.updateById(temp2);
                                            } else {
                                                //没有同类型的账号,直接启用
                                                temp1.setStatus(Constants.ENABLED);
                                                temp1.setChannelId(carDealerId);
                                                channelAccountInfoService.updateById(temp1);
                                            }
                                        }
                                    }
                                }
                            } else if (accountTempListOld.size() == 0) {
                                //没有老账户
                                if (enableAccountTempList.size() > 0 && inApproveAccountTempList.size() > 0) {
                                    for (ChannelReceivablesAccountTemp temp1 : inApproveAccountTempList) {
                                        for (ChannelReceivablesAccountTemp temp2 : enableAccountTempList) { //已启用的
                                            if (temp1.getAccountAttribute().equals(temp2.getAccountAttribute()) && temp1.getCollectionType().equals(temp2.getCollectionType())) {
                                                //同类型的账号,把 审核中的状态设置成启用, 把已启用的状态设置成停用
                                                temp1.setStatus(Constants.ENABLED);
                                                temp2.setStatus(Constants.DISABLE);
                                                temp1.setChannelId(carDealerId);
                                                temp2.setChannelId(carDealerId);
                                                channelAccountInfoService.updateById(temp1);
                                                channelAccountInfoService.updateById(temp2);
                                            } else {
                                                //没有同类型的账号,直接启用
                                                temp1.setStatus(Constants.ENABLED);
                                                temp1.setChannelId(carDealerId);
                                                channelAccountInfoService.updateById(temp1);
                                            }
                                        }
                                    }
                                } else if (enableAccountTempList.size() == 0 && inApproveAccountTempList.size() > 0) {
                                    //没有启用中的收款账号,直接启用审核中的账号即可
                                    for (ChannelReceivablesAccountTemp temp1 : inApproveAccountTempList) {
                                        temp1.setStatus(Constants.ENABLED);
                                        temp1.setChannelId(carDealerId);
                                        channelAccountInfoService.updateById(temp1);
                                    }
                                }
                            } else if (accountTempListOld.size() > 0 && enableAccountTempList.size() == 0) {
                                if (inApproveAccountTempList.size() > 0) {
                                    for (ChannelReceivablesAccountTemp temp1 : inApproveAccountTempList) {
                                        for (ChannelReceivablesAccountTemp temp2 : accountTempListOld) { //老账户
                                            if (temp1.getAccountAttribute().equals(temp2.getAccountAttribute()) && temp1.getCollectionType().equals(temp2.getCollectionType())) {
                                                //同类型的账号,把 审核中的状态设置成启用, 把已启用的状态设置成停用
                                                temp1.setStatus(Constants.ENABLED);
                                                temp2.setStatus(Constants.DISABLE);
                                                temp1.setChannelId(carDealerId);
                                                temp2.setChannelId(carDealerId);
                                                channelAccountInfoService.updateById(temp1);
                                                channelAccountInfoService.updateById(temp2);
                                            } else {
                                                //没有同类型的账号,直接启用
                                                temp1.setStatus(Constants.ENABLED);
                                                temp1.setChannelId(carDealerId);
                                                channelAccountInfoService.updateById(temp1);
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        //更新附件
                        List<ComAttachmentFile> fileList = comAttachmentFileService.list(Wrappers.<ComAttachmentFile>query().lambda()
                                .eq(ComAttachmentFile::getBelongNo, channelId.toString())
                                .eq(ComAttachmentFile::getBusiNo, directCarDealer.getId()));
                        if(CollectionUtil.isNotEmpty(fileList)){
                            for (ComAttachmentFile file : fileList){
                                file.setBusiNo(carDealerId.toString());
                            }
                            comAttachmentFileService.updateBatchById(fileList);
                        }

                        //删品牌
                        channelMainBrandService.remove(Wrappers.<ChannelMainBrand>query().lambda()
                                .eq(ChannelMainBrand::getChannelBelong, Constants.DIRECTCARDEALER)
                                .eq(ChannelMainBrand::getChannelId, carDealerId)
                        );
                        if (mainBrands.size() > 0) {
                            for (ChannelMainBrand brand : mainBrands) {
                                brand.setChannelId(carDealerId);
                            }
                            channelMainBrandService.updateBatchById(mainBrands);
                        }
                        ///看看车商类型
                        String[] businessType = directCarDealer.getBusinessType().split(",");
                        List<String> typeList = Arrays.asList(businessType);
                        boolean newCar = false;
                        boolean oldCar = false;
                        if (typeList.size() > 0) {
                            newCar = typeList.contains(Constants.BUSINESS_TYPE_NEW_CAR);
                            oldCar = typeList.contains(Constants.BUSINESS_TYPE_OLD_CAR);
                        }
                        if (newCar && oldCar) {
                            //新车二手车都有
                            //风控
                            channelRiskInfoService.remove(Wrappers.<ChannelRiskInfoTemp>query().lambda()
                                    .eq(ChannelRiskInfoTemp::getChannelId, carDealerId));
                            //保证金
                            channelQuotaInfoService.remove(Wrappers.<ChannelQuotaInfoTemp>query().lambda()
                                    .eq(ChannelQuotaInfoTemp::getChannelId, carDealerId));
                            //授权区域
                            channelAuthorizeRegionService.remove(Wrappers.<ChannelAuthorizeRegionTemp>query().lambda()
                                    .eq(ChannelAuthorizeRegionTemp::getChannelId, carDealerId));
                            //授权车型
                            channelAuthorizeVehicleTempService.remove(Wrappers.<ChannelAuthorizeVehicleTemp>query().lambda()
                                    .eq(ChannelAuthorizeVehicleTemp::getChannelId, carDealerId));
                        } else if (newCar && !oldCar) {
                            //新车
                            //风控
                            channelRiskInfoService.remove(Wrappers.<ChannelRiskInfoTemp>query().lambda()
                                    .eq(ChannelRiskInfoTemp::getChannelId, carDealerId)
                                    .eq(ChannelRiskInfoTemp::getBusinessType, Constants.BUSINESS_TYPE_NEW_CAR)
                            );
                            //保证金
                            channelQuotaInfoService.remove(Wrappers.<ChannelQuotaInfoTemp>query().lambda()
                                    .eq(ChannelQuotaInfoTemp::getChannelId, carDealerId)
                                    .eq(ChannelQuotaInfoTemp::getBusinessType, Constants.BUSINESS_TYPE_NEW_CAR)
                            );
                            //授权区域
                            channelAuthorizeRegionService.remove(Wrappers.<ChannelAuthorizeRegionTemp>query().lambda()
                                    .eq(ChannelAuthorizeRegionTemp::getChannelId, carDealerId)
                                    .eq(ChannelAuthorizeRegionTemp::getBusinessType, Constants.BUSINESS_TYPE_NEW_CAR)
                            );
                            //授权车型
                            channelAuthorizeVehicleTempService.remove(Wrappers.<ChannelAuthorizeVehicleTemp>query().lambda()
                                    .eq(ChannelAuthorizeVehicleTemp::getChannelId, carDealerId)
                                    .eq(ChannelAuthorizeVehicleTemp::getBusinessType, Constants.BUSINESS_TYPE_NEW_CAR)
                            );
                        } else if (!newCar && oldCar) {
                            //二手车
                            //风控
                            channelRiskInfoService.remove(Wrappers.<ChannelRiskInfoTemp>query().lambda()
                                    .eq(ChannelRiskInfoTemp::getChannelId, carDealerId)
                                    .eq(ChannelRiskInfoTemp::getBusinessType, Constants.BUSINESS_TYPE_OLD_CAR)
                            );
                            //保证金
                            channelQuotaInfoService.remove(Wrappers.<ChannelQuotaInfoTemp>query().lambda()
                                    .eq(ChannelQuotaInfoTemp::getChannelId, carDealerId)
                                    .eq(ChannelQuotaInfoTemp::getBusinessType, Constants.BUSINESS_TYPE_OLD_CAR)
                            );
                            //授权区域
                            channelAuthorizeRegionService.remove(Wrappers.<ChannelAuthorizeRegionTemp>query().lambda()
                                    .eq(ChannelAuthorizeRegionTemp::getChannelId, carDealerId)
                                    .eq(ChannelAuthorizeRegionTemp::getBusinessType, Constants.BUSINESS_TYPE_OLD_CAR)
                            );
                            //授权车型
                            channelAuthorizeVehicleTempService.remove(Wrappers.<ChannelAuthorizeVehicleTemp>query().lambda()
                                    .eq(ChannelAuthorizeVehicleTemp::getChannelId, carDealerId)
                                    .eq(ChannelAuthorizeVehicleTemp::getBusinessType, Constants.BUSINESS_TYPE_OLD_CAR)
                            );
                        }
                        //风控信息
                        if (riskInfoTempList.size() > 0) {
                            for (ChannelRiskInfoTemp temp : riskInfoTempList) {
                                temp.setChannelId(carDealerId);
                            }
                            channelRiskInfoService.updateBatchById(riskInfoTempList);
                        }
                        //额度信息
                        if (quotaInfoTempList.size() > 0) {
                            for (ChannelQuotaInfoTemp temp : quotaInfoTempList) {
                                temp.setChannelId(carDealerId);
                            }
                            channelQuotaInfoService.updateBatchById(quotaInfoTempList);
                        }
                        //授权区域
                        if (regionTempList.size() > 0) {
                            for (ChannelAuthorizeRegionTemp temp : regionTempList) {
                                temp.setChannelId(carDealerId);
                            }
                            channelAuthorizeRegionService.updateBatchById(regionTempList);
                        }
                        //授权车型
                        if (vehicleTempList.size() > 0) {
                            for (ChannelAuthorizeVehicleTemp temp : vehicleTempList) {
                                temp.setChannelId(carDealerId);
                            }
                            channelAuthorizeVehicleTempService.updateBatchById(vehicleTempList);
                        }
                        directCarDealerService.removeById(directCarDealer.getId());
                        directCarDealer.setId(carDealerId);

                        if (directCarDealer.getChannelStatus() != null || newCar) {
                            directCarDealer.setChannelStatus(Constants.ENABLED);
                        }
                        if (directCarDealer.getChannelStatusOldCar() != null || oldCar) {
                            directCarDealer.setChannelStatusOldCar(Constants.ENABLED);
                        }

                        directCarDealerService.updateById(directCarDealer);

                    } else {
                        if (directCarDealer.getChannelStatus() != null) {
                            directCarDealer.setChannelStatus(Constants.ENABLED);
                        }
                        if (directCarDealer.getChannelStatusOldCar() != null) {
                            directCarDealer.setChannelStatusOldCar(Constants.ENABLED);
                        }
                        //没有这个车商,更新状态即可
                        directCarDealerService.updateById(directCarDealer);

                    }
                    //改关联表状态
                    if (coopeCardealerTemps.size() > 0) {
                        for (ChannelCoopeCardealerTemp temp : coopeCardealerTemps) {
                            temp.setStatus(Constants.ENABLED);
                            temp.setApproveRemark(remark);
                            temp.setCardealerId(directCarDealer.getId());
                            channelCoopeCardealerService.updateById(temp);
                        }
                    }

                    if (node.equals("end")) {
                        //财务审核后 更新账户状态
                        List<ChannelReceivablesAccountTemp> accountTempList = channelAccountInfoService.list(Wrappers.<ChannelReceivablesAccountTemp>query().lambda()
                                .eq(ChannelReceivablesAccountTemp::getChannelId, directCarDealer.getId())
                                .eq(ChannelReceivablesAccountTemp::getStatus, Constants.REVIEW)
                        );
                        if (accountTempList.size() > 0) {
                            for (ChannelReceivablesAccountTemp temp : accountTempList) {
                                temp.setStatus(Constants.ENABLED);
                                channelAccountInfoService.updateById(temp);
                            }
                        }
                        List<ChannelReceivablesAccountTemp> allAccountTempList = channelAccountInfoService.list(Wrappers.<ChannelReceivablesAccountTemp>query().lambda()
                                .eq(ChannelReceivablesAccountTemp::getChannelId, directCarDealer.getId())
                        );
                        directCarDealerToCase.setChannelAccountInfoList(allAccountTempList);
                    }

                    //同步到案件服务
                    directCarDealerToCase.setChannelBaseInfoTemp(directCarDealer);
                    directCarDealerToCase.setChannelCoopeCardealerTemp(coopeCardealerTemps.get(0));
                    directCarDealerToCase.setMainBrandList(mainBrands);
                    directCarDealerToCase.setChannelRiskInfoList(riskInfoTempList);
                    directCarDealerToCase.setChannelQuotaInfoTempList(quotaInfoTempList);
                    directCarDealerToCase.setChannelAuthorizeRegionList(regionTempList);
                    directCarDealerToCase.setChannelAuthorizeVehicleList(vehicleTempList);
                    //******************同步到案件服务**************
                    saveDirectCarDealerInfoToCase(directCarDealerToCase);
                }
            }
            //删除剩余节点数据信息
            for (int i = 0; i < assignList.size(); i++) {
                workTaskAssignService.removeById(assignList.get(i).getId());
            }
            return IResponse.success("提交成功");
        } else {
            return IResponse.fail("提交失败,提交指令异常，请确认！");
        }

    }


    /**
     * 同步直营车商信息到案件服务公用方法
     */

    public void saveDirectCarDealerInfoToCase(DirectCarDealerCondition condition) {
        //同步数据到案件服务
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("clientId", channelConfig.getCaseClientId());
        headers.put("clientSecret", channelConfig.getCaseClientSecret());
        Assert.isTrue((boolean)channelUseCaseService.saveDirectCarDealer(condition, headers).getData(),"操作失败,请重试!");
    }


}
